package com.example.xianji.wxapi;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.activity.Main_BaiKe_DetailActivity;
import com.example.xianji.activity.Main_LoginActivity;
import com.example.xianji.XJApplication;
import com.example.xianji.R.layout;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth.Resp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.widget.Toast;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final String WEIXIN_SCOPE = "snsapi_userinfo";// 用于请求用户信息的作用域
    private static final String WEIXIN_STATE = "login_state"; // 自定义
    private String APP_ID = "wx79e902dceb15b8bb";
    private String APP_SECRET = "31c11987ca6ad6014eef5f0caf93935d";
    private IWXAPI api;
    public static String code;

    /*public static String wenxin_nickname, unionid, headimgurl;
    public static String openid, access_token;*/
//    private SharedPreferences sp;
//    private Editor ed;
    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
				/*XJApplication.cachThreadPool.execute(new Runnable() {

					@Override
					public void run() {
						getUID(openid, access_token);
					}
				});*/

            }

            /*
             * if(msg.what==2){ XJApplication.cachThreadPool.execute(new
             * Runnable() {
             *
             * @Override public void run() {
             * getUID(openid,access_token); } });
             *
             * }
             */
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(layout.activity_wxentry);

        api = WXAPIFactory.createWXAPI(this, APP_ID, true);
        api.handleIntent(getIntent(), this);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);
        api.handleIntent(intent, this);

    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq arg0) {
        // finish();
    }

    /**
     * 请求响应回调接口
     */
    @Override
    public void onResp(BaseResp resp) {
        String result = null;
        if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
            /************ 微信登录 *****************/
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    Resp sendAuthResp = (Resp) resp;// 用于分享时不要有这个，不能强转
                    code = sendAuthResp.code;
                    result = "同意授权";
				/*XJApplication.cachThreadPool.execute(new Runnable() {

					@Override
					public void run() {
						getResult(code);

					}
				});*/
                    Main_LoginActivity.weixin_login_success = true;
                    finish();
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    result = "取消";
                    finish();
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    result = "拒绝授权";
                    finish();
                    break;
                default:

                    break;

            }
        } else if (resp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
            /**********************分享回调**********************************/
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    Toast.makeText(WXEntryActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
                    /*********************如果是点击百科详情页的分享,得调分享接口************************/
                    if (Contant.Click_WeiXin_Share == 1) {
                        XJApplication.cachThreadPool.execute(new Runnable() {

                            @Override
                            public void run() {
                                get_share_data();
                            }
                        });
                        Contant.Click_WeiXin_Share = 0;
                    }
                    finish();
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    result = "取消";
                    finish();
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    result = "拒绝授权";
                    finish();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 获取openid accessToken值用于后期操作
     *
     * @param code
     *            请求码
     *//*
	private void getResult(final String code) {

		Log.i("获取codecoedexoedd", "获取codecoedexoedd");

		final String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
				+ APP_ID
				+ "&secret="
				+ APP_SECRET
				+ "&code="
				+ code
				+ "&grant_type=authorization_code";
		XJApplication.cachThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				JsonObjectRequest request = new JsonObjectRequest(Method.GET,
						path, null, new Listener<JSONObject>() {

							@Override
							public void onResponse(JSONObject response) {

								Log.i("dddddddd", response + "ddddddddd");

								try {

									openid = response.getString("openid")
											.toString().trim();
									access_token = response
											.getString("access_token")
											.toString().trim();
									handler.sendEmptyMessage(1);

								} catch (JSONException e) {
									e.printStackTrace();
								}

							}

						}, new Response.ErrorListener() {

							@Override
							public void onErrorResponse(VolleyError error) {

							}
						});
				XJApplication.getHttpQueues().cancelAll("abcPost");
				request.setTag("abcPost");
				request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1,
						1.0f));
				XJApplication.getHttpQueues().add(request);
				XJApplication.getHttpQueues().start();

				
				 * HttpUtils httpUtils=new HttpUtils();
				 * httpUtils.send(HttpMethod.GET, path, new
				 * RequestCallBack<String>() {
				 * 
				 * @Override public void onFailure(HttpException arg0, String
				 * arg1) {
				 * 
				 * }
				 * 
				 * @Override public void onSuccess(ResponseInfo<String> arg0) {
				 * arg0.result); try { JSONObject object=new
				 * JSONObject(arg0.result); openid = object.getString("openid")
				 * .toString().trim(); access_token = object
				 * .getString("access_token").toString().trim();
				 * handler.sendEmptyMessage(1);
				 * 
				 * } catch (JSONException e) {
				 * block e.printStackTrace(); }
				 * 
				 * 
				 * } });
				 
			}
		});
		
		 * new Thread() {// 开启工作线程进行网络请求 public void run() {
		 * 
		 * 
		 * 
		 * 
		 * 
		 * return; }; }.start();
		 
	}*/
    /*
     *//**
     * 获取用户唯一标识
     *
     * @param openId
     * @param accessToken
     *//*
	private void getUID(final String openId, final String accessToken) {

		String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
				+ accessToken + "&openid=" + openId;

		JsonObjectRequest request = new JsonObjectRequest(Method.GET, path,
				null, new Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject response) {
						Log.i("dddddddd", response + "ddddddddd");
						try {
							wenxin_nickname = response.getString("nickname");
							unionid = response.getString("unionid");
							headimgurl = response.getString("headimgurl");
							
							
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
					}
				});
		XJApplication.getHttpQueues().cancelAll("abcPost");
		request.setTag("abcPost");
		request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
		XJApplication.getHttpQueues().add(request);
		XJApplication.getHttpQueues().start();

		
		 * HttpUtils http=new HttpUtils(); http.send(HttpMethod.GET, path, new
		 * RequestCallBack<String>() {
		 * 
		 * @Override public void onFailure(HttpException arg0, String arg1) { //
		 * 
		 * }
		 * 
		 * @Override public void onSuccess(ResponseInfo<String> arg0) {
		 * Auto-generated method stub
		 * 
		 * Log.i("ccccccccccc", arg0.result); JSONObject obj; try { obj = new
		 * JSONObject(arg0.result);
		 * 
		 * wenxin_nickname = obj.getString("nickname"); unionid =
		 * obj.getString("unionid"); headimgurl=obj.getString("headimgurl");
		 * 
		 * 
		 * 
		 * } catch (JSONException e) {
		 * e.printStackTrace(); }
		 * 
		 * finish(); } });
		 

	}*/

    /******************** 百科详情页面获取分享接口 *************************/
    public void get_share_data() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        parms.addBodyParameter("wid", Main_BaiKe_DetailActivity.baike_detail_id + "");// 百科id

        httpUtils.send(HttpMethod.POST, Contant.baike_share, parms,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        try {
                            JSONObject OBJECT = new JSONObject(arg0.result);
                            if (OBJECT.getInt("status") == 1) {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }
}
